package com.axinfu.util;

import java.util.Map;
import java.util.TreeMap;

/**
 * util:签名处理
 *
 * @author zjn
 * @since 2022/3/23
 */
public class SignUtil {

    private SignUtil() {
    }

    /**
     * 将参数map按照key排序
     *
     * @param params 参数map
     * @return 排序后map
     */
    public static Map<String, String> sort4string(Map<String, String> params) {
        Map<String, String> sortMap = new TreeMap<>(String::compareTo);
        sortMap.putAll(params);
        return sortMap;
    }

    /**
     * 将参数map按照key排序
     *
     * @param params 参数map
     * @return 排序后map
     */
    public static Map<String, String> sort4object(Map<String, Object> params) {
        Map<String, String> sortMap = new TreeMap<>(String::compareTo);
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            sortMap.put(entry.getKey(), String.valueOf(entry.getValue()));
        }
        return sortMap;
    }

    /**
     * 获取参数map按照key排序并使用url格式组装结果
     *
     * @param params 参数map
     * @return 组装结果
     */
    public static String getKvStr4String(Map<String, String> params) {
        Map<String, String> sortMap = sort4string(params);
        return getKvStrBySortMap(sortMap);
    }

    /**
     * 获取参数map按照key排序并使用url格式组装结果
     *
     * @param params 参数map
     * @return 组装结果
     */
    public static String getKvStr4Object(Map<String, Object> params) {
        Map<String, String> sortMap = sort4object(params);
        return getKvStrBySortMap(sortMap);
    }

    /**
     * getKvStrBySortMap
     *
     * @param sortMap sortMap
     * @return String
     */
    private static String getKvStrBySortMap(Map<String, String> sortMap) {
        StringBuilder signStrSb = new StringBuilder();
        for (Map.Entry<String, String> entry : sortMap.entrySet()) {
            signStrSb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
        }
        return signStrSb.length() > 0 ? signStrSb.substring(1) : signStrSb.toString();
    }
}
